package com.hzy.config;

import com.hzy.constant.Constants;
import com.hzy.ums.domain.vo.LoginMemberVo;
import com.hzy.ums.domain.vo.MemberVo;
import com.hzy.ums.service.IMemberService;
import com.hzy.ums.service.TokenService;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Configuration
public class WebMemberInterceptor extends HandlerInterceptorAdapter {

  @Autowired
  private TokenService tokenService;

  @Autowired
  private IMemberService memberService;

  private static String[] WHITE_PATHS = {
          "/login",
          "/register",
          "/validate",
          "/captchaSms",
          "/captchaEmail",
          "/captchaImage"
  };

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    String requestUri = request.getRequestURI();
    boolean flag = true;
    if (!requestUri.startsWith("/h5/")) {
      return super.preHandle(request, response, handler);
    }

    for (String s : WHITE_PATHS) {
      if (requestUri.startsWith(s)) {
        flag = false;
        break;
      }
    }
    if (!flag) {
      return super.preHandle(request, response, handler);
    }
    LoginMemberVo loginMember = tokenService.getLoginMember(request);
    if (loginMember == null) {
      throw new ServiceException("获取用户ID异常", HttpStatus.UNAUTHORIZED);
    }
    tokenService.verifyMemberToken(loginMember);
    //获取会员信息
    MemberVo member = memberService.queryById(loginMember.getMemberId());
    if (member == null || member.getStatus() == 0) {
      throw new ServiceException("获取用户ID异常", HttpStatus.UNAUTHORIZED);
    }
    //将会员信息存放至全局
    LocalDataUtil.setVar(Constants.MEMBER_INFO, member);

    return super.preHandle(request, response, handler);
  }



}
